<!DOCTYPE html>
<html>
<head>
	<base href="/">
<title>Personal Profile Form Widget Flat Responsive Widget Template</title>
<!-- for-mobile-apps -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="keywords" content="Personal Profile Form Widget Responsive, Login form web template, Sign up Web Templates, Flat Web Templates, Login signup Responsive web template, Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<!-- //for-mobile-apps -->
<link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="/personalinformation/css/j-forms.css">
<link href="/personalinformation/css/style.css" rel="stylesheet" type="text/css" media="all" />
	<style>
		.address-container {
			width: 100%;
			max-width: 700px;
		}

		.address-item {
			background: #fff;
			border: 1px solid #e0e0e0;
			padding: 15px;
			margin-bottom: 15px;
			border-radius: 8px;
			box-shadow: 0 2px 4px rgba(0,0,0,0.05);
		}

		.address-info {
			margin-bottom: 10px;
		}

		.user-info {
			margin-bottom: 8px;
		}

		.user-info .name {
			font-weight: bold;
			margin-right: 15px;
		}

		.user-info .phone {
			color: #666;
		}

		.address-detail {
			color: #333;
			line-height: 1.5;
		}

		.address-actions {
			margin-top: 10px;
			text-align: right;
		}

		.address-actions button {
			padding: 5px 15px;
			margin-left: 10px;
			border-radius: 4px;
			border: none;
			cursor: pointer;
		}

		.address-actions button:first-child {
			background: #2196F3;
			color: white;
		}

		.address-actions button:last-child {
			background: #f44336;
			color: white;
		}

		.form-group {
			margin-bottom: 15px;
		}

		.form-group label {
			display: inline-block;
			width: 100px;
			font-weight: bold;
		}

		.form-group input,
		.form-group select {
			width: 200px;
			padding: 8px;
			border: 1px solid #ddd;
			border-radius: 4px;
		}
	</style>
</head>
<body>



<!-- 修改左侧导航栏，使用data-target属性而不是href -->
<div class="user-sidebar" style="position: fixed; left: 0; top: 0; width: 200px; height: 100%; background-color: #f8f8f8; border-right: 1px solid #e7e7e7; padding: 20px 0; box-shadow: 2px 0 5px rgba(0,0,0,0.1);">
	<div class="sidebar-header" style="text-align: center; padding: 20px 0; border-bottom: 1px solid #e7e7e7;">
		<h3 style="margin: 0; color: #333;">个人中心</h3>
	</div>
	<ul style="list-style: none; padding: 0; margin: 20px 0;">
		<li style="padding: 10px 20px; margin-bottom: 5px; background-color: #e7e7e7; font-weight: bold;" class="nav-item active">
			<a href="javascript:void(0);" data-target="personal-info" style="text-decoration: none; color: #333; display: block;">我的信息</a>
		</li>
		<li style="padding: 10px 20px; margin-bottom: 5px;" class="nav-item">
			<a href="javascript:void(0);" data-target="my-orders" style="text-decoration: none; color: #333; display: block;">我的订单</a>
		</li>
		<li style="padding: 10px 20px; margin-bottom: 5px;" class="nav-item">
			<a href="javascript:void(0);" data-target="my-address" style="text-decoration: none; color: #333; display: block;">收货地址</a>
		</li>
		<li style="padding: 10px 20px; margin-bottom: 5px;" class="nav-item">
			<a href="javascript:void(0);" data-target="change-password" style="text-decoration: none; color: #333; display: block;">修改密码</a>
		</li>
<!--		<li style="padding: 10px 20px; margin-bottom: 5px;" class="nav-item">-->
<!--			<a href="javascript:void(0);" data-target="my-favorites" style="text-decoration: none; color: #333; display: block;">我的收藏</a>-->
<!--		</li>-->
<!--		<li style="padding: 10px 20px; margin-bottom: 5px;" class="nav-item">-->
<!--			<a href="javascript:void(0);" data-target="my-reviews" style="text-decoration: none; color: #333; display: block;">我的评价</a>-->
<!--		</li>-->
		<li style="padding: 10px 20px; margin-bottom: 5px;" class="nav-item">
			<a href="javascript:void(0);" onclick="goToIndex()" style="text-decoration: none; color: #333; display: block;">返回首页</a>
		</li>
	</ul>
</div>

<!-- 调整主内容区域，添加内容容器 -->
<div class="content" style="margin-left: 220px; padding-top: 20px;">

	<!-- 个人信息内容区域 -->
	<div id="personal-info" class="content-section active">
		<h1>Personal Profile form widget</h1>
		<div class="main w3l">
			<!-- 原有的个人信息表单内容 -->
			<div class="im-g" style="max-width: 200px; margin: 0 auto;">
				<img src="/personalinformation/images/img1.jpg" alt="" id="userAvatar" style="width: 100%; height: auto; border-radius: 50%;">
				<div class="image-upload" style="display:none; margin-top:10px; text-align:center;">
					<input type="file" id="imageUpload" accept="image/*" style="display:none;">
					<button type="button" id="uploadBtn" class="layui-btn layui-btn-primary layui-btn-sm">更换头像</button>
				</div>
			</div>

			<form class="contact-forms wthree">
					<div class="main-row">
						<div class="input">
							<input type="text" placeholder="username" id="username" name="username" required="">
						</div>
					</div>

				<div class="main-row">
					<div class="input">
						<input type="hidden" placeholder="password" id="password" name="password" required="">
					</div>
				</div>
				<div class="main-row">
					<div class="input">
						<input type="text" placeholder="nickname" id="nickname" name="nickname" required="">
					</div>
				</div>
				<div class="main-row">
					<div class="input">
						<input type="text" placeholder="phone" id="phone" name="phone" required="">
					</div>
				</div>
				<div class="footer">
					<button type="button" class="primary-btn">编辑</button>
					<button type="button" class="secondary-btn">保存</button>
				</div>
			</form>

		</div>
	</div>
		
</div>

<!--我的订单-->
<!--我的订单-->
<div id="my-orders" class="content-section" style="display: none;">
	<h3 style="text-align: center; margin-bottom: 20px; color: #333;">我的订单</h3>
	<div class="orders-container" style="max-width: 800px; margin: 0 auto;">
		<!-- 订单数据将在这里动态加载 -->
	</div>
</div>

<!-- 其他内容保持不变 -->

<!--我的地址-->
<div class="content" id="my-address" style="margin-left: 220px; padding: 20px; display: flex; justify-content: center;">
	<!-- 我的地址内容区域 -->
	<div  class="tab-pane" style="width: 100%; max-width: 800px;">
		<h3 style="text-align: center; margin-bottom: 20px; color: #333;">我的收货地址</h3>

		<!-- 地址列表容器 -->
		<div id="address-list" class="address-container" style="margin: 0 auto;">
			<!-- 地址列表将在这里动态渲染 -->
		</div>

		<!-- 添加新地址按钮 -->
		<div class="add-address" style="text-align: center; margin-top: 20px;">
			<button class="add-address-btn" onclick="showAddressForm()"
					style="background: #4CAF50; color: white; border: none; padding: 10px 20px;
                           border-radius: 4px; cursor: pointer;">
				添加新地址
			</button>
		</div>
		<!-- 添加/编辑地址表单 -->
		<div id="address-form" class="address-form" style="display: none; max-width: 600px;
     margin: 20px auto; background: #fff; padding: 20px; border-radius: 8px;
     box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
			<h3 class="form-title">添加新地址</h3>
			<form id="userAddressForm">
				<input type="hidden" id="addressId" name="id">
				<div class="form-group">
					<label>收货人姓名：</label>
					<input type="text" id="receiver" name="name" required style="width: 200px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
				</div>
				<div class="form-group">
					<label>手机号码：</label>
					<input type="tel" id="useraddress-phone" name="phone" required style="width: 200px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
				</div>
				<div class="form-group">
					<label>所在地区：</label>
					<div style="display: inline-block;">
						<select id="province" name="province" required style="width: 120px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 5px;">
							<option value="">请选择省份</option>
						</select>

						<select id="city" name="city" required style="width: 120px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 5px;">
							<option value="">请选择城市</option>
						</select>

						<select id="state" name="state" required style="width: 120px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
							<option value="">请选择区县</option>
						</select>
					</div>
				</div>
				<div class="form-group">
					<label>详细地址：</label>
					<input type="text" id="address" name="address" required style="width: 400px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
				</div>
				<!-- 添加默认地址复选框 -->
				<div class="form-group">
					<label>
						<input type="checkbox" id="set-default" name="isdefault"> 设为默认地址
					</label>
				</div>
				<div class="form-actions" style="text-align: center; margin-top: 20px;">
					<button type="button" onclick="saveAddress()" style="background: #2196F3; color: white; border: none; padding: 8px 20px; border-radius: 4px; margin-right: 10px;">保存</button>
					<button type="button" onclick="cancelEdit()" style="background: #f44336; color: white; border: none; padding: 8px 20px; border-radius: 4px;">取消</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!--修改密码-->
<div id="change-password" class="content-section" style="display: none;">
	<h3 style="text-align: center; margin-bottom: 20px; color: #333;">修改密码</h3>
	<div class="main w3l">
		<form id="passwordForm" class="contact-forms wthree">
			<div class="main-row">
				<div class="input">
					<input type="password" placeholder="当前密码" id="prepassword" name="oldPassword" required="">
				</div>
			</div>
			<div class="main-row">
				<div class="input">
					<input type="password" placeholder="新密码" id="newpassword" name="newPassword" required="">
				</div>
			</div>
			<div class="main-row">
				<div class="input">
					<input type="password" placeholder="确认新密码" id="confirmpassword" name="confirmPassword" required="">
				</div>
			</div>
			<div class="footer">
				<button type="button" id="savePasswordBtn" class="secondary-btn">保存修改</button>
			</div>
		</form>
	</div>
</div>


<!--我的收藏-->
<!--<div id="my-favorites" class="content-section" style="display: none;">-->
<!--	<h1>Personal Profile form widget</h1>-->
<!--	<div class="main w3l">-->
<!--		<form class="contact-forms wthree">-->
<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="username" id="username4" name="username" required="">-->
<!--				</div>-->
<!--			</div>-->

<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="password" id="password4" name="password" required="">-->
<!--				</div>-->
<!--			</div>-->
<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="nickname" id="nickname4" name="nickname" required="">-->
<!--				</div>-->
<!--			</div>-->
<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="phone" id="phone4" name="phone" required="">-->
<!--				</div>-->
<!--			</div>-->
<!--			<div class="footer">-->
<!--				<button type="button" class="primary-btn">编辑</button>-->
<!--				<button type="button" class="secondary-btn">保存</button>-->
<!--			</div>-->
<!--		</form>-->

<!--	</div>-->
<!--</div>-->

<!--我的评价-->
<!--<div id="my-reviews" class="content-section" style="display: none;">-->
<!--	<h1>Personal Profile form widget</h1>-->
<!--	<div class="main w3l">-->
<!--		<form class="contact-forms wthree">-->
<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="username" id="username5" name="username" required="">-->
<!--				</div>-->
<!--			</div>-->

<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="password" id="password5" name="password" required="">-->
<!--				</div>-->
<!--			</div>-->
<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="nickname" id="nickname5" name="nickname" required="">-->
<!--				</div>-->
<!--			</div>-->
<!--			<div class="main-row">-->
<!--				<div class="input">-->
<!--					<input type="text" placeholder="phone" id="phone5" name="phone" required="">-->
<!--				</div>-->
<!--			</div>-->
<!--			<div class="footer">-->
<!--				<button type="button" class="primary-btn">编辑</button>-->
<!--				<button type="button" lay-submit lay-filter="editsave" class="secondary-btn">保存</button>-->
<!--			</div>-->
<!--		</form>-->

<!--	</div>-->
<!--</div>-->

		<!-- Scripts -->
		<script src="/personalinformation/js/jquery.1.11.1.min.js"></script>

		<!--[if lt IE 10]>
				<script src="j-folder/js/jquery.placeholder.min.js"></script>
			<![endif]-->
<script src="layui/layui.all.js"></script>


<script>

	function goToIndex() {
		console.log('正在跳转到首页...');
		location.href = '/shopping/index';
	}

const $=layui.$;
	/*$(document).ready(function() {*/
	// 页面加载时获取用户信息
	loadUserInfo();

	// 初始状态下禁用输入框
	disableInputs();

	// 编辑按钮点击事件
	$(".primary-btn").click(function () {
		enableInputs();
	});

	// 保存按钮点击事件
	$(".secondary-btn").click(function () {
		saveUserInfo();
	});

	// 上传按钮点击事件
	$("#uploadBtn").click(function () {
		$("#imageUpload").click();
	});

	// 图片选择后预览
	$("#imageUpload").change(function () {
		if (this.files && this.files[0]) {
			var reader = new FileReader();
			reader.onload = function (e) {
				$("#userAvatar").attr('src', e.target.result);
				window.imageChanged = true;
			}
			reader.readAsDataURL(this.files[0]);
		}
	});

	// 获取用户信息的函数
	function loadUserInfo() {
		$.ajax({
			url: '/user/list',
			type: 'GET',
			dataType: 'json',
			success: function (response) {
				console.log("用户信息响应:", response);

				if (response && response.data) {
					var userData = Array.isArray(response.data) ? response.data[0] : response.data;

					if (userData) {
						// 保存用户ID和图片URL供后续使用
						window.currentUserId = userData.id;

						// 确保imgurl是字符串
						if (userData.imgurl) {
							if (typeof userData.imgurl === 'object') {
								// 如果是对象，设置为空字符串
								window.currentUserImgUrl = '';
								console.error("错误的图片URL格式(对象):", userData.imgurl);
							} else if (userData.imgurl === "[object Object]") {
								// 如果是字符串"[object Object]"，也设置为空
								window.currentUserImgUrl = '';
								console.error("错误的图片URL格式(字符串):", userData.imgurl);
							} else {
								window.currentUserImgUrl = userData.imgurl;
							}
						} else {
							window.currentUserImgUrl = '';
						}

						window.imageChanged = false;

						// 填充用户数据到表单
						$("#username").val(userData.username || '');
						// $("#password").val(userData.password || '');
						$("#nickname").val(userData.nickname || '');
						$("#phone").val(userData.phone || '');

						// 如果有头像，显示用户头像
						if (window.currentUserImgUrl && window.currentUserImgUrl !== '' &&
								window.currentUserImgUrl !== "[object Object]") {
							var imgPath = window.currentUserImgUrl;
							// 移除可能存在的 shopping/ 前缀
							imgPath = imgPath.replace('/shopping', '');
							$("#userAvatar").attr('src', imgPath);
						} else {
							// 使用默认头像
							$("#userAvatar").attr('src', '/personalinformation/images/img1.jpg');
						}

						// 禁用输入框
						disableInputs();
					} else {
						layer.msg('未找到用户数据');
					}
				} else {
					layer.msg('获取用户信息失败');
				}
			},
			error: function (xhr, status, error) {
				console.error("获取用户信息失败:", error);
				layer.msg('获取用户信息失败: ' + error);
			}
		});
	}

	// 上传图片并保存用户信息
	function uploadImageAndSaveInfo() {
		var formData = new FormData();
		formData.append('file', $("#imageUpload")[0].files[0]);

		$.ajax({
			url: '/file/upload',
			type: 'POST',
			data: formData,
			processData: false,
			contentType: false,
			dataType: 'text',  // 期望服务器返回纯文本
			success: function (response) {
				console.log("图片上传响应类型:", typeof response);
				console.log("图片上传响应:", response);

				try {
					// 清理响应中可能的额外JSON字符
					var cleanResponse = response;
					if (typeof response === 'string') {
						// 尝试提取文件名部分
						var fileNameMatch = response.match(/([^\/\\&\?]+\.\w{3,4})/);
						if (fileNameMatch && fileNameMatch[0]) {
							cleanResponse = fileNameMatch[0];
							console.log("提取的文件名:", cleanResponse);
						} else if (response.includes('.jpg') || response.includes('.png') || response.includes('.jpeg') || response.includes('.gif')) {
							// 如果包含图片扩展名，尝试提取
							var extMatch = response.match(/([^\/\\&\?]+\.(jpg|png|jpeg|gif))/i);
							if (extMatch && extMatch[0]) {
								cleanResponse = extMatch[0];
								console.log("提取的图片名:", cleanResponse);
							}
						} else if (response.trim().startsWith('{')) {
							// 尝试解析JSON
							var jsonResponse = JSON.parse(response);
							if (jsonResponse.data) {
								cleanResponse = jsonResponse.data;
							} else if (jsonResponse.url) {
								cleanResponse = jsonResponse.url;
							}
						}
					}

					// 确保URL是有效的
					if (cleanResponse && typeof cleanResponse === 'string' &&
							cleanResponse.trim() !== '' &&
							cleanResponse !== "[object Object]") {

						// 如果URL包含额外的JSON字符，进一步清理
						if (cleanResponse.includes('"}]}')) {
							cleanResponse = cleanResponse.split('"}]}')[0];
							if (cleanResponse.includes('.jpg') || cleanResponse.includes('.png') ||
									cleanResponse.includes('.jpeg') || cleanResponse.includes('.gif')) {
								console.log("清理后的URL:", cleanResponse);
							} else {
								cleanResponse += '.jpg'; // 添加默认扩展名
							}
						}

						// 添加easyfile/前缀，如果还没有的话
						if (!cleanResponse.startsWith('easyfile/') && !cleanResponse.startsWith('/easyfile/')) {
							cleanResponse = 'easyfile/' + cleanResponse;
						}

						window.currentUserImgUrl = cleanResponse.trim();
						console.log("最终设置的图片URL:", window.currentUserImgUrl);

						// 立即保存用户信息
						saveUserInfoWithImage(window.currentUserImgUrl);
					} else {
						console.error("无效的图片URL:", response);
						layer.msg('图片上传失败：无法获取有效的URL', {icon: 2});
					}
				} catch (e) {
					console.error("解析响应出错:", e);
					layer.msg('图片上传失败：响应格式错误', {icon: 2});
				}
			},
			error: function (xhr, status, error) {
				console.error("图片上传失败:", error);
				layer.msg('图片上传失败：' + error, {icon: 2});
			}
		});
	}

	// 使用指定的图片URL保存用户信息
	function saveUserInfoWithImage(imageUrl) {
		var userData = {
			id: window.currentUserId,
			username: $("#username").val().trim(),
			password: $("#password").val().trim(),
			nickname: $("#nickname").val().trim(),
			phone: $("#phone").val().trim(),
			imgurl: imageUrl
		};

		console.log("保存带图片的用户信息:", userData);

		$.ajax({
			url: '/user/edit',
			type: 'POST',
			contentType: 'application/x-www-form-urlencoded',
			traditional: true,
			data: userData,
			success: function (response) {
				console.log("保存响应:", response);
				if (response === 1 || response.code === 0 || response === "1") {
					layer.msg('保存成功', {icon: 1});
					window.imageChanged = false;
					disableInputs();
					loadUserInfo();
				} else {
					layer.msg('保存失败：' + (response.msg || '请稍后重试'), {icon: 2});
				}
			},
			error: function (xhr, status, error) {
				console.error("保存失败:", error, xhr.responseText);
				layer.msg('保存失败：' + error, {icon: 2});
			}
		});
	}

	// 保存用户信息
	function saveUserInfo() {
		if (window.imageChanged && $("#imageUpload")[0].files[0]) {
			// 如果图片已更改，先上传图片
			uploadImageAndSaveInfo();
		} else {
			// 如果图片未更改，直接保存信息
			saveUserInfoOnly();
		}
	}

	// 仅保存用户信息
	function saveUserInfoOnly() {
		// 确保 imgurl 是有效的字符串
		var imgUrl = '';
		if (window.currentUserImgUrl) {
			if (typeof window.currentUserImgUrl === 'string' &&
					window.currentUserImgUrl !== "[object Object]") {
				imgUrl = window.currentUserImgUrl;
			}
		}

		var userData = {
			id: window.currentUserId,
			username: $("#username").val().trim(),
			password: $("#password").val().trim(),
			nickname: $("#nickname").val().trim(),
			phone: $("#phone").val().trim(),
			imgurl: imgUrl
		};

		console.log("保存的图片URL:", imgUrl);
		console.log("保存用户信息:", userData);

		$.ajax({
			url: '/user/edit',
			type: 'POST',
			contentType: 'application/x-www-form-urlencoded',
			traditional: true,
			data: userData,
			success: function (response) {
				console.log("保存响应:", response);
				if (response === 1 || response.code === 0 || response === "1") {
					// layer.msg('保存成功', {icon: 1});
					window.imageChanged = false;
					disableInputs();
					loadUserInfo();
				} else {
					layer.msg('保存失败：' + (response.msg || '请稍后重试'), {icon: 2});
				}
			},
			error: function (xhr, status, error) {
				console.error("保存失败:", error, xhr.responseText);
				layer.msg('保存失败：' + error, {icon: 2});
			}
		});
	}

	/// 禁用输入框 - 修改为只影响个人信息表单
	function disableInputs() {
		$("#personal-info input").prop('disabled', true);
		$("#personal-info .secondary-btn").prop('disabled', true);
		$(".image-upload").hide();
	}

	// 启用输入框 - 修改为只影响个人信息表单
	function enableInputs() {
		$("#personal-info input").prop('disabled', false);
		$("#personal-info .secondary-btn").prop('disabled', false);
		$(".image-upload").show();
	}

// 添加导航点击事件处理
$(".nav-item a").click(function (e) {
	e.preventDefault();
	var target = $(this).data("target");

	// 移除所有导航项的活动状态
	$(".nav-item").css("background-color", "").css("font-weight", "normal");
	$(this).parent().css("background-color", "#e7e7e7").css("font-weight", "bold");

	// 如果是个人信息，显示当前页面内容
	if (target === "personal-info") {
		$("#personal-info").show();
		$("#my-orders").hide();
		$("#my-address").hide();
		$("#change-password").hide();
		$("#my-favorites").hide();
		$("#my-reviews").hide();

	} else {
		// 其他页面内容，先隐藏当前内容
		$("#personal-info").hide();

		// 加载对应内容
		loadContent(target);
	}
});

// 加载内容的函数 - 删除这个重复的函数定义
function loadContent(target) {
	// 隐藏所有内容区域
	$(".content-section").hide();
	$("#my-address").hide();

	if (target === "my-address") {
		$("#my-address").css("display", "flex");
		// 加载地址列表
		loadUserAddresses();
		// 初始化省份下拉框
		initProvinceSelect();
	} else if (target === "my-orders") {
		// 显示订单区域
		$("#my-orders").show();
		// 加载订单数据
		loadUserOrders();
	} else {
		// 显示对应的内容区域
		$("#" + target).show();
	}
}


/*});*/

// 页面加载完成后执行


// 修改表单验证函数
function validateAddressForm(data) {
	if (!data.name) {
		layer.msg('请输入收货人姓名');
		return false;
	}
	if (!data.phone) {
		layer.msg('请输入手机号码');
		return false;
	}
	if (!/^1[3-9]\d{9}$/.test(data.phone)) {
		layer.msg('请输入正确的手机号码');
		return false;
	}
	if (!data.province || !data.city || !data.state) {
		layer.msg('请选择完整的收货地址');
		return false;
	}
	if (!data.address) {
		layer.msg('请输入详细地址');
		return false;
	}
	return true;
}
// 页面加载完成后执行
// 加载内容的函数 - 删除这个重复的函数定义，它覆盖了前面的函数
// function loadContent(target) {
// 	// 隐藏所有内容区域
// 	$(".content-section").hide();
// 	$("#my-address").hide();

// 	if (target === "my-address") {
// 		$("#my-address").css("display", "flex");
// 		// 加载地址列表
// 		loadUserAddresses();
// 		// 初始化省份下拉框
// 		initProvinceSelect();
// 	} else {
// 		// 显示对应的内容区域
// 		$("#" + target).show();
// 	}
// }


// 编辑地址
			function editAddress(id) {
				/*const useraddressId=$(this).closest(".address-item").data("addressid");*/
				$.ajax({
					url: `/useraddress/getuseraddressbyid?id=${id}`, // 修改为正确的获取地址信息接口
					type: 'GET',
					success: function (response) {
						if (response.code == 0) {
							const useraddress = response.data;
							fillAddressForm(useraddress);
							$('#address-form .form-title').text('编辑地址');
							$('#address-form').show();
							$('.add-address-btn').hide();

							/*LoadProvinces(useraddress.province, useraddress.city, useraddress.state);*/
						} else {
							layer.msg(response.msg || '获取地址信息失败');
						}
					},
					error: function (xhr, status, error) {
						layer.msg('获取地址信息失败: ' + error);
					}
				});
			}

// 显示地址表单
			function showAddressForm() {
				resetForm();
				$('#address-form .form-title').text('添加新地址');
				$('#address-form').show();
				$('.add-address-btn').hide();
			}

// 初始化省市区数据
			const amapKey = "d5e466c74f37e2b1f89163a68a161ea7";

	// 修复省市区三级联动功能
	function LoadProvinces(selectedProvince = "", selectedCity = "", selectedArea = "") {
		const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=中国&subdistrict=1&extensions=base`;

		$.ajax({
			url: url,
			type: 'GET',
			success: function (response) {
				if (response.status === "1") {
					const provinces = response.districts[0].districts;
					$("#province").empty().append('<option value="">请选择省份</option>');
					provinces.forEach(province => {
						$("#province").append(`<option value="${province.name}">${province.name}</option>`);
					});

					// 设置选中的省份并触发加载城市
					if (selectedProvince) {
						$("#province").val(selectedProvince);
						loadCities(selectedProvince, selectedCity, selectedArea);
					}
				}
			}
		});
	}

	// 加载城市数据
	function loadCities(provinceName, selectedCity = "", selectedArea = "") {
		if (!provinceName) return;

		const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=${encodeURIComponent(provinceName)}&subdistrict=1&extensions=base`;

		$.ajax({
			url: url,
			type: 'GET',
			success: function (response) {
				if (response.status === "1" && response.districts && response.districts[0]) {
					const cities = response.districts[0].districts;
					$("#city").empty().append('<option value="">请选择城市</option>');
					cities.forEach(city => {
						$("#city").append(`<option value="${city.name}">${city.name}</option>`);
					});

					// 设置选中的城市并触发加载区域
					if (selectedCity) {
						$("#city").val(selectedCity);
						loadAreas(selectedCity, selectedArea);
					}
				}
			}
		});
	}

	// 加载区域数据
	function loadAreas(cityName, selectedArea = "") {
		if (!cityName) return;

		const url = `https://restapi.amap.com/v3/config/district?key=${amapKey}&keywords=${encodeURIComponent(cityName)}&subdistrict=1&extensions=base`;

		$.ajax({
			url: url,
			type: 'GET',
			success: function (response) {
				if (response.status === "1" && response.districts && response.districts[0]) {
					const areas = response.districts[0].districts;
					$("#state").empty().append('<option value="">请选择区域</option>');
					areas.forEach(area => {
						$("#state").append(`<option value="${area.name}">${area.name}</option>`);
					});

					// 设置选中的区域
					if (selectedArea) {
						$("#state").val(selectedArea);
					}
				}
			}
		});
	}

	// 初始化省份下拉框
	function initProvinceSelect() {
		LoadProvinces();

		// 监听省份变化
		$('#province').off('change').on('change', function () {
			const province = $(this).val();
			$("#city").empty().append('<option value="">请选择城市</option>');
			$("#state").empty().append('<option value="">请选择区域</option>');
			if (province) {
				loadCities(province);
			}
		});

		// 监听城市变化
		$('#city').off('change').on('change', function () {
			const city = $(this).val();
			$("#state").empty().append('<option value="">请选择区域</option>');
			if (city) {
				loadAreas(city);
			}
		});
	}

	// 保存地址
	function saveAddress() {
		// 检查用户ID是否存在
		if (!window.currentUserId) {
			layer.msg('用户未登录，请先登录');
			return;
		}

		// 获取表单数据
		const formData = {
			useraddressid: $('#addressId').val() || null,  // 使用正确的主键名
			userid: window.currentUserId,
			name: $('#receiver').val().trim(),
			phone: $('#useraddress-phone').val().trim(),
			province: $('#province').val(),
			city: $('#city').val(),
			state: $('#state').val(),
			address: $('#address').val().trim(),
			isdefault: $('#set-default').is(':checked') ? 1 : 0
		};

		// 如果是新增地址，删除useraddressid字段
		if (!formData.useraddressid) {
			delete formData.useraddressid;
		}

		// 表单验证
		if (!validateAddressForm(formData)) {
			return;
		}

		// 确定是新增还是编辑
		const url = formData.useraddressid ? '/useraddress/edit' : '/useraddress/add';

		console.log('提交的地址数据:', formData);

		$.ajax({
			url: url,
			type: 'POST',
			contentType: 'application/x-www-form-urlencoded',
			data: formData,
			success: function(response) {
				console.log('保存地址响应:', response);
					if(response&&response.code===0) {
						layer.msg('保存成功');
						cancelEdit();
						loadUserAddresses();
					}


			},
			error: function(xhr, status, error) {
				console.error('保存地址失败:', xhr.responseText);
				layer.msg('保存失败: ' + error);
			}
		});
	}

			// 加载用户地址列表
			function loadUserAddresses() {
				$.ajax({
					url: '/useraddress/list',
					type: 'GET',
					success: function (response) {
						if (response.code === 0) {
							renderAddressList(response.data);
						} else {
							layer.msg(response.msg || '加载地址失败');
						}
					}
				});
			}

	// 渲染地址列表
	function renderAddressList(addresses) {
		const container = $('#address-list');
		container.empty();

		if (addresses && addresses.length > 0) {
			addresses.forEach(useraddress => {  // 修改变量名为useraddress
				container.append(`
                <div class="address-item" data-id="${useraddress.useraddressid}">
                    <div class="address-info">
                        <div class="user-info">
                            <span class="name">${useraddress.name}</span>
                            <span class="phone">${useraddress.phone}</span>
                            ${useraddress.isdefault === 1 ? '<span class="default-tag" style="color: #ff4400; margin-left: 10px; font-size: 12px;">[默认地址]</span>' : ''}
                        </div>
                        <div class="address-detail">
                            ${useraddress.province} ${useraddress.city} ${useraddress.state} ${useraddress.address}
                        </div>
                        <div class="default-address">
                            <input type="checkbox" class="default-checkbox"
                                ${useraddress.isdefault === 1 ? 'checked' : ''}
                                onchange="setDefaultAddress(${useraddress.useraddressid}, this)">
                            <label>设为默认地址</label>
                        </div>
                    </div>
                    <div class="address-actions">
                        <button onclick="editAddress(${useraddress.useraddressid})">编辑</button>
                        <button onclick="deleteAddress(${useraddress.useraddressid})">删除</button>
                    </div>
                </div>
            `);
			});
		} else {
			container.html('<div class="no-address">暂无收货地址</div>');
		}
	}

	// 填充表单数据
	function fillAddressForm(useraddress) {  // 修改参数名为useraddress
		$('#addressId').val(useraddress.useraddressid);
		$('#receiver').val(useraddress.name);
		$('#useraddress-phone').val(useraddress.phone);

		// 使用LoadProvinces加载省市区数据
		LoadProvinces(useraddress.province, useraddress.city, useraddress.state);

		$('#address').val(useraddress.address);
		$('#set-default').prop('checked', useraddress.isdefault === 1);

		// 确保所有输入框都是启用状态
		$('#address-form input').prop('disabled', false);
		$('#address-form select').prop('disabled', false);
	}

			// 显示地址表单
			function showAddressForm() {
				resetForm();
				$('#address-form').show();
				$('.add-address-btn').hide();
			}


			// 删除地址
			function deleteAddress(id) {
				layer.confirm('确定要删除这个地址吗？', {
					btn: ['确定', '取消']
				}, function () {
					$.ajax({
						url: `/useraddress/delete?id=${id}`,
						type: 'POST',
						success: function (response) {
							if (response.code === 0) {
								layer.msg('删除成功');
								loadUserAddresses();
							} else {
								layer.msg(response.msg || '删除失败');
							}
						}
					});
				});
			}

			// 取消编辑
			function cancelEdit() {
				$('#address-form').hide();
				$('.add-address-btn').show();
				resetForm();
			}

			// 重置表单
			function resetForm() {
				$('#userAddressForm')[0].reset();
				$('#addressId').val('');
			}


	// 设置默认地址
	function setDefaultAddress(addressId, checkbox) {
		if (!addressId) {
			layer.msg('地址ID不能为空');
			checkbox.checked = false;
			return;
		}

		// 获取当前复选框的状态
		const isDefault = checkbox.checked ? 1 : 0;

		// 如果是设置为默认，取消其他地址的默认状态
		if (isDefault === 1) {
			$('.default-checkbox').not(checkbox).prop('checked', false);
		}

		$.ajax({
			url: '/useraddress/setdefault',
			type: 'POST',
			data: {
				id: addressId,
				isdefault: isDefault
			},
			success: function(response) {
				console.log('设置默认地址响应:', response);
				if (response.code === 0) {
					layer.msg(isDefault === 1 ? '设置默认地址成功' : '取消默认地址成功');
					// 强制刷新地址列表，确保UI状态与后端一致
					setTimeout(function() {
						loadUserAddresses();
					}, 300);
				} else {
					layer.msg(response.msg || '操作失败');
					// 恢复复选框原来的状态
					checkbox.checked = !checkbox.checked;
				}
			},
			error: function(xhr, status, error) {
				console.error('操作失败:', xhr.responseText);
				layer.msg('操作失败: ' + error);
				// 恢复复选框原来的状态
				checkbox.checked = !checkbox.checked;
			}
		});
	}





//显示商品信息








// 定义全局变量存储当前页码和总页数
var currentPage = 1;
var totalPages = 1;

// 修改加载用户订单函数，添加分页参数
function loadUserOrders(page = 1) {
	console.log("开始加载用户订单，页码：" + page);
	$.ajax({
		url: '/order/list',
		type: 'GET',
		data: {
			limit: 10,  // 设置每页显示数量
			page: page  // 设置当前页码
		},
		success: function(response) {
			console.log('订单数据响应:', response);

			// 检查是否有数据
			if (response && response.data && response.data.length > 0) {
				// 更新当前页码和总页数
				currentPage = page;
				totalPages = Math.ceil(response.count / 10);

				// 渲染订单列表
				renderOrderList(response.data);

				// 渲染分页控件
				renderPagination(currentPage, totalPages);
			} else {
				// 显示暂无数据提示
				$('.orders-container').html(`
					<div style="text-align: center; padding: 20px;">
						<p>暂无订单数据</p>
						<a href="/shopping/index" class="btn" style="background-color: #76aa6f; color: white; padding: 8px 15px; border-radius: 4px; text-decoration: none; display: inline-block; margin-top: 10px;">
							去购物
						</a>
					</div>
				`);
				// 隐藏分页控件
				$('.pagination-container').hide();
			}
		},
		error: function(xhr, status, error) {
			console.error('获取订单失败:', error, xhr.responseText);
			$('.orders-container').html('<div style="text-align: center; padding: 20px;">加载订单失败，请稍后重试</div>');
			// 隐藏分页控件
			$('.pagination-container').hide();
		}
	});
}

// 添加分页控件渲染函数
function renderPagination(currentPage, totalPages) {
	// 创建分页容器，如果不存在
	if ($('.pagination-container').length === 0) {
		$('.orders-container').after('<div class="pagination-container" style="text-align: center; margin-top: 20px;"></div>');
	}

	const paginationContainer = $('.pagination-container');
	paginationContainer.empty();

	// 如果总页数小于等于1，不显示分页
	if (totalPages <= 1) {
		paginationContainer.hide();
		return;
	}

	paginationContainer.show();

	// 创建分页HTML
	let paginationHtml = '<div class="pagination" style="display: inline-block;">';

	// 上一页按钮
	paginationHtml += `<button class="page-btn prev-btn" ${currentPage <= 1 ? 'disabled' : ''} style="padding: 8px 15px; margin: 0 5px; border: 1px solid #ddd; background-color: ${currentPage <= 1 ? '#f5f5f5' : '#fff'}; color: ${currentPage <= 1 ? '#aaa' : '#333'}; border-radius: 4px; cursor: ${currentPage <= 1 ? 'not-allowed' : 'pointer'};">上一页</button>`;

	// 页码显示
	paginationHtml += `<span class="page-info" style="margin: 0 10px; display: inline-block; line-height: 38px;">第 ${currentPage} 页 / 共 ${totalPages} 页</span>`;

	// 下一页按钮
	paginationHtml += `<button class="page-btn next-btn" ${currentPage >= totalPages ? 'disabled' : ''} style="padding: 8px 15px; margin: 0 5px; border: 1px solid #ddd; background-color: ${currentPage >= totalPages ? '#f5f5f5' : '#fff'}; color: ${currentPage >= totalPages ? '#aaa' : '#333'}; border-radius: 4px; cursor: ${currentPage >= totalPages ? 'not-allowed' : 'pointer'};">下一页</button>`;

	paginationHtml += '</div>';

	paginationContainer.html(paginationHtml);

	// 绑定分页按钮事件
	$('.prev-btn').click(function() {
		if (currentPage > 1) {
			loadUserOrders(currentPage - 1);
		}
	});

	$('.next-btn').click(function() {
		if (currentPage < totalPages) {
			loadUserOrders(currentPage + 1);
		}
	});
}

// 在页面加载时执行
$(document).ready(function() {
	// 初始化导航切换
	$('.nav-item a').click(function() {
		var target = $(this).data('target');
		$('.content-section').hide();
		$('#' + target).show();
		$('.nav-item').removeClass('active');
		$(this).parent().addClass('active');

		// 如果切换到订单页面，加载订单数据
		if (target === 'my-orders') {
			loadUserOrders(1); // 从第1页开始加载
		}
	});

	// 页面加载时执行
	loadUserInfo();

	// 如果当前是订单页面，加载订单数据
	if ($('#my-orders').is(':visible')) {
		loadUserOrders(1); // 从第1页开始加载
	}
});

// 渲染订单列表
function renderOrderList(orders) {
	const container = $('.orders-container');
	container.empty();

	orders.forEach(order => {
		// 获取订单状态文本
		let statusText = '未知状态';
		let statusColor = '#9e9e9e';

		switch(order.status) {
			case -1:
				statusText = '已失效';
				statusColor='#9e9e9e';
				break;
			case 0:
				statusText = '待付款';
				statusColor = '#ff6b6b';
				break;
			case 1:
				statusText = '待发货';
				statusColor = '#ff9800';
				break;
			case 2:
				statusText = '待收货';
				statusColor = '#2196F3';
				break;
			case 3:
				statusText = '已收货';
				statusColor = '#4CAF50';
				break;
			case 4:
				statusText = '已完成';
				statusColor = '#9e9e9e';
				break;
		}

		// 格式化日期
		let formattedDate = '未知时间';
		if (order.addtime) {
			try {
				// 处理不同格式的日期
				const orderDate = new Date(order.addtime);
				formattedDate = orderDate.toLocaleString('zh-CN');
			} catch (e) {
				console.error('日期格式化错误:', e);
			}
		}

		// 创建订单操作按钮
		let actionButtons = '';

		// 根据订单状态添加不同的按钮
		if (order.status === 0) {
			// 待付款状态，添加去支付按钮
			actionButtons = `
			<button onclick="goToPay(${order.orderid})" style="background: #76aa6f; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; margin-right: 10px;">去支付</button>
			<button onclick="deleteOrder(${order.orderid}, ${order.userid})" style="background: #f44336; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">删除订单</button>
			<button onclick="viewOrderDetail(${order.orderid})" style="background: #f44336; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">订单详情</button>
		`;
		}
		else if(order.status === 1||order.status === 2){
				// 其他状态只显示删除按钮
				actionButtons = `
			<button onclick="deleteOrder(${order.orderid}, ${order.userid})" style="background: #f44336; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">删除订单</button>
			<button onclick="viewOrderDetail(${order.orderid})" style="background: #f44336; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">订单详情</button>
			<button onclick="changeOrderDetail(${order.orderid})" style="background: #f44336; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">收货</button>
		`;
			}
		else {
			// 其他状态只显示删除按钮
			actionButtons = `
			<button onclick="deleteOrder(${order.orderid}, ${order.userid})" style="background: #f44336; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">删除订单</button>
			<button onclick="viewOrderDetail(${order.orderid})" style="background: #f44336; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">订单详情</button>
		`;
		}

		// 创建订单项HTML
		const orderHtml = `
            <div class="order-item" style="background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 20px; padding: 15px;">
                <div class="order-header" style="display: flex; justify-content: space-between; padding-bottom: 10px; border-bottom: 1px solid #eee;">
                    <div class="order-info">
                        <span class="order-number" style="font-weight: bold; margin-right: 15px;">订单号: ${order.code || order.orderid}</span>
                        <span class="order-date" style="color: #666;">下单时间: ${formattedDate}</span>
                    </div>
                    <div class="order-status" style="color: ${statusColor}; font-weight: bold;">${statusText}</div>
                </div>
                <div class="order-footer" style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px; margin-top: 10px; border-top: 1px solid #eee;">
                    <div class="order-total">
                        <span style="font-weight: bold;">订单总额: </span>
                        <span style="color: #ff6b6b; font-size: 18px; font-weight: bold;">¥${order.money ? order.money.toFixed(2) : '0.00'}</span>
                    </div>
                    <div class="order-actions">
                        ${actionButtons}
                    </div>
                </div>
            </div>
        `;

		container.append(orderHtml);
	});
}

// 查看订单详情
function viewOrderDetail(orderId) {
	// 跳转到订单详情页面
	window.location.href = `/shopping/orderdetails?orderid=${orderId}`;
}


// 添加去支付的函数
function goToPay(orderId) {
	if (!orderId) {
		layer.msg('订单ID不能为空');
		return;
	}
	// 跳转到支付页面
	window.location.href = `/shopping/payment?orderid=${orderId}`;
}

	// 删除订单
	function deleteOrder(orderId, userId) {
	layer.confirm('确定要删除这个订单吗？', {
		btn: ['确定', '取消']
	}, function() {
		$.ajax({
			url: '/order/delete',
			type: 'POST',
			data: {
				orderid: orderId,
				userid: userId
			},
			success: function(response) {
				if (response > 0) {
					layer.msg('删除成功');
					loadUserOrders(); // 重新加载订单列表
				} else {
					layer.msg('删除失败，请稍后重试');
				}
			},
			error: function(xhr, status, error) {
				layer.msg('删除失败：' + error);
				console.error('删除订单失败:', error, xhr.responseText);
			}
		});
	});
}


	// 修改订单
	function changeOrderDetail(orderId) {
		layer.confirm('确定要收货吗？', {
			btn: ['确定', '取消']
		}, function() {
			$.ajax({
				url: '/order/edit',
				type: 'POST',
				data: {
					orderid: orderId,
					status: 3,
				},
				success: function(response) {
					if (response.code===0) {
						layer.msg('收货成功');
						loadUserOrders(); // 重新加载订单列表
					} else {
						layer.msg('收货失败，请稍后重试');
					}
				},
				error: function(xhr, status, error) {
					layer.msg('删除失败：' + error);
					console.error('删除订单失败:', error, xhr.responseText);
				}
			});
		});
	}







</script>
//结算
<script>
// 修改密码相关代码
$(document).ready(function() {
	// 修改密码按钮点击事件
	$("#savePasswordBtn").click(function() {
		// 获取表单数据
		const oldPassword = $("#prepassword").val() || "";
		const newPassword = $("#newpassword").val() || "";
		const confirmPassword = $("#confirmpassword").val() || "";

		// 表单验证
		if (!oldPassword.trim()) {
			layer.msg('请输入当前密码', {icon: 2});
			return;
		}

		if (!newPassword.trim()) {
			layer.msg('请输入新密码', {icon: 2});
			return;
		}

		if (newPassword.trim().length < 6 || newPassword.trim().length > 16) {
			layer.msg('新密码长度应为6-16位', {icon: 2});
			return;
		}

		if (!confirmPassword.trim()) {
			layer.msg('请确认新密码', {icon: 2});
			return;
		}

		if (newPassword.trim() !== confirmPassword.trim()) {
			layer.msg('两次输入的新密码不一致', {icon: 2});
			return;
		}

		if (oldPassword.trim() === newPassword.trim()) {
			layer.msg('新密码不能与当前密码相同', {icon: 2});
			return;
		}

		// 先验证当前密码是否正确
		$.ajax({
			url: '/user/verifyPassword',
			type: 'POST',
			data: {
				password: oldPassword
			},
			success: function(response) {
				if (response.code === 0) {
					// 当前密码验证成功，继续修改密码
					updatePassword(oldPassword, newPassword);
				} else {
					layer.msg(response.msg || '当前密码不正确', {icon: 2});
				}
			},
			error: function(xhr, status, error) {
				console.error("验证密码失败:", error);
				layer.msg('验证密码失败: ' + error, {icon: 2});
			}
		});
	});

	// 更新密码的函数
	function updatePassword(oldPassword, newPassword) {
		$.ajax({
			url: '/user/changePassword',
			type: 'POST',
			data: {
				oldPassword: oldPassword,
				newPassword: newPassword
			},
			success: function(response) {
				console.log("修改密码响应:", response);

				// 修改这里的判断逻辑
				if (response && response.code === 0) {
					layer.msg('密码修改成功', {icon: 1});
					// 清空表单
					$("#passwordForm")[0].reset();
					setTimeout(function(){
						//跳转到我的订单页面
						location.href="/shopping/login"
					},1800)
				} else {
					// 显示具体的错误信息
					layer.msg(response.msg || '密码修改失败', {icon: 2});
				}
			},
			error: function(xhr, status, error) {
				console.error("修改密码失败:", error);
				layer.msg('修改密码失败: ' + error, {icon: 2});
			}
		});

	}
});

</script>

<script>
	// 在页面加载完成后执行
	$(document).ready(function() {
		// 检查URL中是否有tab参数
		const urlParams = new URLSearchParams(window.location.search);
		const tabParam = urlParams.get('tab');

		// 如果有tab参数，触发对应的导航项点击
		if (tabParam) {
			// 找到对应的导航项并触发点击
			$(".nav-item a[data-target='" + tabParam + "']").click();

			// 如果是my-orders，确保加载订单数据
			if (tabParam === "my-orders") {
				// 如果已经定义了loadUserOrders函数，调用它
				if (typeof loadUserOrders === 'function') {
					loadUserOrders();
				}
			}
			if(tabParam==="personal-info"){
				if (typeof loadUserOrders === 'function') {
					loadUserInfo();
				}
			}
		}
	});
</script>




</body>
</html>
